﻿namespace OpenAdmin.Application.Services;

/// <summary>
/// api接口服务类
/// </summary>
public class ApiResourceService : ServiceBase, IApiResourceService, ITransientDependency
{
    private readonly IRepository<SysApiResource, ApplicationDbContextLocator> _apiResourceRepository;
    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="apiResourceRepository"></param>
    public ApiResourceService(IRepository<SysApiResource, ApplicationDbContextLocator> apiResourceRepository)
    {
        _apiResourceRepository = apiResourceRepository;
    }
    /// <summary>
    /// 分页获取接口列表
    /// </summary>
    /// <param name="requestDto"></param>
    /// <returns></returns>
    public async Task<PagedList<ApiResourcesByPageResponseDto>> GetApiResourcesByPage(ApiResourcesByPageRequestDto requestDto)
    {
        var apiResourceQueryable = _apiResourceRepository.Entities.AsQueryable();
        if (!string.IsNullOrWhiteSpace(requestDto.Keyworld))
        {
            apiResourceQueryable = apiResourceQueryable.Where(p => p.Name.Contains(requestDto.Keyworld) || p.LinkUrl.Contains(requestDto.Keyworld));
        }
        var pagedList = await apiResourceQueryable.ProjectToType<ApiResourcesByPageResponseDto>()
            .ToPagedListAsync(p => p.CreateTime, requestDto.PageIndex, requestDto.PageSize);

        return pagedList;
    }

    /// <summary>
    /// 获取全部接口列表
    /// </summary>
    /// <returns></returns>
    public async Task<List<ApiResourcesResponseDto>> GetApiResources()
    {
        var apiResources = await _apiResourceRepository.Entities.OrderBy(p => p.Sort).ProjectToType<ApiResourcesResponseDto>().ToListAsync();
        return apiResources;
    }

    /// <summary>
    /// 添加接口
    /// </summary>
    /// <param name="requestDto"></param>
    /// <returns></returns>
    public async Task AddApiResource(AddApiResourceRequestDto requestDto)
    {
        requestDto.LinkUrl = requestDto.LinkUrl.ToLower();

        var apiResource = await _apiResourceRepository.Entities.SingleOrDefaultAsync(p => p.LinkUrl == requestDto.LinkUrl);
        apiResource.ThrowIf(p => p != null, "该接口地址已存在");

        apiResource = _mapper.Map<SysApiResource>(requestDto);
        apiResource.CreateTime = DateTime.Now;
        apiResource.CreateBy = UserIdentity.UserId;
        await _apiResourceRepository.Entities.AddAsync(apiResource);

        var result = await _apiResourceRepository.SaveChangesAsync();
        result.ThrowIf(p => p == 0, "添加接口失败");
    }

    /// <summary>
    /// 更新接口信息
    /// </summary>
    /// <param name="requestDto"></param>
    public async Task EditApiResource(EditApiResourceRequestDto requestDto)
    {
        var apiResource = await _apiResourceRepository.Entities.FindAsync(requestDto.Id);
        apiResource.ThrowIfNull("接口不存在");

        requestDto.LinkUrl = requestDto.LinkUrl.ToLower();

        var anyApiResource = await _apiResourceRepository.Entities.FirstOrDefaultAsync(p => p.Id != requestDto.Id && p.LinkUrl == requestDto.LinkUrl);
        anyApiResource.ThrowIf(p => p != null, "该接口地址已存在");

        apiResource.Name = requestDto.Name;
        apiResource.Code = requestDto.Code;
        apiResource.LinkUrl = requestDto.LinkUrl;
        apiResource.Sort = requestDto.Sort;
        apiResource.ModifyBy = UserIdentity.UserId;
        apiResource.ModifyTime = DateTime.Now;

        var uResult = await _apiResourceRepository.SaveChangesAsync();
        uResult.ThrowIf(p => p == 0, "更新接口失败");
    }

    /// <summary>
    /// 删除接口
    /// </summary>
    /// <param name="id"></param>
    public async Task DeleteApiResource(int id)
    {
        var apiResource = await _apiResourceRepository.Entities.FindAsync(id);
        apiResource.ThrowIfNull("接口不存在");

        apiResource.IsDeleted = true;

        var dResult = await _apiResourceRepository.SaveChangesAsync();
        dResult.ThrowIf(p => p == 0, "删除接口失败");
    }
}
